package dataDAOImpl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;



import dataConnector.Connector;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.ICommodityDAO;
import dataDTO.CommodityDTO;

public class MySQLCommodityDAO implements ICommodityDAO {

	@Override
	public CommodityDTO getCommodity(int commodityId) throws DALException {
		ResultSet rs = Connector.doQuery("SELECT*FROM raavare WHERE raavare_id = " + commodityId);
		try{
			if(!rs.first()) throw new DALException ("The commodity " + commodityId + " dont exist");
			return new CommodityDTO(rs.getInt(1), rs.getString(2), rs.getString(3));
		}
		catch (SQLException e) {throw new DALException (e);}
	}

	@Override
	public List<CommodityDTO> getCommodityList() throws DALException {
		List<CommodityDTO> list = new ArrayList<CommodityDTO>();
		ResultSet rs = Connector.doQuery("SELECT*FROM raavare");
		try{
			while(rs.next())
			{
				list.add(new CommodityDTO(rs.getInt(1), rs.getString(2), rs.getString(3)));
			}
		}
		catch (SQLException e) {throw new DALException(e);}
		return list;
	}

	@Override
	public void createCommodity(CommodityDTO commodity) throws DALException {
		Connector.doUpdate("INSERT INTO raavare(raavare_id,raavare_navn,leverandoer) VALUES"+
				"("+ commodity.getCommodityId()+ ",'" + commodity.getCommodityName()+ "','"+ commodity.getSupplier() + "')");
	}

	@Override
	public void updateCommodity(CommodityDTO commodity) throws DALException {
		Connector.doUpdate("UPDATE raavare SET raavare_id = '" + commodity.getCommodityId() + "', raavare_navn = '" + commodity.getCommodityName()
				+ "', leverandoer = '"+ commodity.getSupplier() + "' WHERE raavare_id = " + commodity.getCommodityId());
		
	}

}
